package com.ibeetl.springboot.ch6.conf;

import javax.sql.DataSource;

import com.ibeetl.starter.BeetlSqlMutipleSourceCustomize;
import org.beetl.sql.core.DefaultConnectionSource;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import com.ibeetl.starter.BeetlSqlCustomize;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
public class DataSourceConfig {

	@Autowired
	ApplicationContext ctx;

	@Primary
	@Bean(name = "a")
	public DataSource datasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		return ds;
	}

	@Bean(name = "a-1")
	public DataSource slaveDatasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		return ds;
	}

	@Bean
	public BeetlSqlMutipleSourceCustomize beetlSqlCustomize() {
		return new BeetlSqlMutipleSourceCustomize() {
			@Override
			public void customize(String dataSource, SQLManager sqlManager) {
				if(dataSource.equals("a")){
					DefaultConnectionSource defaultConnectionSource = (DefaultConnectionSource)sqlManager.getDs();
					DataSource slave = (DataSource)ctx.getBean("a-1");
					defaultConnectionSource.setSlaves(new DataSource[]{slave});

				}
			}

		};
	}
}